package com.fable.utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by weishuai on 15-11-24.
 */
public class ExcelUtil {
    private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);


    private final static String excel2003L =".xls";    //2003- 版本的excel
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel

    /**
     * 导出excle
     * @param sheetMapList 导出的数据源头支持导出多个sheet
     *                     比如导出两个sheet:
     *                     List<Map<String,Object>> sheetMapList=new ArrayList()
     *                     map key:sheet, list,
     * @param fileName 导出的文件名
     * @param response
     */
    public static void exportExcel(List<Map> sheetMapList, String fileName, HttpServletResponse response) {
        OutputStream out = null;
        try {
            Workbook wb = new XSSFWorkbook();
            Font font = wb.createFont();
            CellStyle cellStyle = wb.createCellStyle();
            font.setFontHeightInPoints((short) 10);//设置字体大小
            cellStyle.setFont(font);
            cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 左右居中

            for (Map m : sheetMapList) {
                Sheet sheet = wb.createSheet(getString("sheet", m));
                List<List<String>> list = (List<List<String>>) m.get("list");
                for (int j = 0; j < list.size(); j++) {//行
                    Row row = sheet.createRow((short) j);
                    List<String> l = list.get(j);
                    for (int i = 0; i < l.size(); i++) {//列
                        Cell cell = row.createCell(i);
                        if (isNumber(String.valueOf(l.get(i)))) {
                            cell.setCellValue(Double.valueOf(String.valueOf(l.get(i))));
                        } else {
                            cell.setCellValue(l.get(i));
                        }
                        cell.setCellStyle(cellStyle);
                    }
                }
            }

            response.reset();
            response.setContentType("application/ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + java.net.URLEncoder.encode(fileName, "UTF-8") + ".xlsx\"");
            out = response.getOutputStream();

            wb.write(out);
            out.flush();
            out.close();

        } catch (IOException e) {
            log.error("excel error", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    log.error("excel close error", e);
                }
            }
        }
    }

    public static String getString(String key, Map m) {
        if (m == null || key == null || m.get(key) == null) {
            return null;
        }
        return String.valueOf(m.get(key));
    }

    public static boolean isNumber(String str){
        if(!StringUtils.isBlank(str)){
            return str.matches("[0-9]+");
        }else{
            return false;
        }
    }




    /**
     * 描述：获取IO流中的数据，组装成List<List<Object>>对象
     * @param in,fileName
     * @return
     * @throws IOException
     */
    public static List<List<Object>> importExcel(InputStream in, String fileName, boolean allSheet) throws Exception{
        List<List<Object>> list = null;

        //创建Excel工作薄
        Workbook work = getWorkbook(in,fileName);
        if(null == work){
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        list = new ArrayList<List<Object>>();
        //是否所有sheet都解析,默认只解析第一个
        int length=1;
        if(allSheet){
            length= work.getNumberOfSheets();
        }
        //遍历Excel中所有的sheet
        for (int i = 0; i < length; i++) {
            sheet = work.getSheetAt(i);
            if(sheet==null){continue;}

            //遍历当前sheet中的所有行
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                if(row==null||row.getFirstCellNum()==j){
                    continue;
                }

                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                int x=0;
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    Object o=getCellValue(cell);
                    //记录该行的列为空的个数
                    if(o==null||"".equals(o)){
                        x++;
                    }
                    li.add(o);
                }
                //如果该列的为空个数和总列数相同则跳过
                if(x==li.size()){
                    continue;
                }
                list.add(li);
            }
        }
        //work.close();

        return list;
    }

    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public static  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if(excel2003L.equals(fileType)){
            wb = new HSSFWorkbook(inStr);  //2003-
        }else if(excel2007U.equals(fileType)){
            wb = new XSSFWorkbook(inStr);  //2007+
        }else{
            throw new Exception("解析的文件格式有误！");
        }
        return wb;
    }

    /**
     * 描述：对表格中数值进行格式化
     * @param cell
     * @return
     */
    public static Object getCellValue(Cell cell){
        Object value = null;
        DecimalFormat df = new DecimalFormat("0");  //格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化
        DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字

        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if("General".equals(cell.getCellStyle().getDataFormatString())){
                    value = df.format(cell.getNumericCellValue());
                }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
                    value = sdf.format(cell.getDateCellValue());
                }
                else if("yy/m/d".equals(cell.getCellStyle().getDataFormatString())){
                    value = sdf.format(cell.getDateCellValue());
                }
                else if("yyyy/mm/dd".equals(cell.getCellStyle().getDataFormatString())){
                    value = sdf.format(cell.getDateCellValue());
                }
                else if("yyyy-mm-dd".equals(cell.getCellStyle().getDataFormatString())){
                    value = sdf.format(cell.getDateCellValue());
                }
                else if("yyyy-mm-dd HH:mm:ss".equals(cell.getCellStyle().getDataFormatString())){
                    value = sdf.format(cell.getDateCellValue());
                }
                else{
                    value = df2.format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            default:
                break;
        }
        return value;
    }

    /**
     * 获取请求ip
     *
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String[] arr = StringUtils.split(ip, ",");
        if (arr != null && arr.length > 0) {
            return arr[0].trim();
        }
        return ip;
    }



}
